<template>
  <div>
    <div>
      <BreakSpace label="客源信息" :containerStyle="{ marginBottom: '10px' }"/>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="3"
        :labelWidth="110"
        :formType="type"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
      <BreakSpace label="意向车型信息" :containerStyle="{ marginBottom: '10px' }"/>
      <FilterTable
        ref="carTable"
        :columns="columns"
        height="auto"
        :datakey="'intentDTOList'"
        :dataSource="cartablelist"
        :isPagination=false
        :isColumnFilter=false
        :isToperInfo=false
        :isSelectColumn=false
        :onColumnsChange="columns => this.columns = columns"
      />
      <BreakSpace label="联系信息" :containerStyle="{ marginBottom: '10px' }"/>
      <FilterTable
        ref="contactTable"
        :columns="contactColumns"
        height="auto"
        :datakey="'customerContactinfoDTOList'"
        :dataSource="contacttablelist"
        :isPagination=false
        :isColumnFilter=false
        :isToperInfo=false
        :isSelectColumn=false
        :onColumnsChange="columns => this.columns = columns"
      />
      <BreakSpace label="战败信息" :containerStyle="{ marginBottom: '10px' }"/>
      <FormPanel
        ref="downFormPanel"
        :list="downFormList"
        :cols="3"
        :labelWidth="110"
        :formType="type"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
      <BreakSpace label="战败回访" :containerStyle="{ marginBottom: '10px' }"/>
      <FormPanel
        ref="feedbackFormPanel"
        :list="feedbackFormList"
        :cols="3"
        :labelWidth="110"
        :formType="type"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
      <BreakSpace label="问卷" :containerStyle="{ marginBottom: '10px' }"/>
      <div v-html="questionnaire"></div>
    </div>
    <div
      :style="{
        position: 'inherit',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <el-button v-if="type !== 'show'" @click="saveDialog" type="primary">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { formatdate } from '@/utils/index';
import {
  saveFeedback,
  getQuestionnaire,
  getAllHeatUp
} from '@/api/customerCare/saleVisit/downfeedback';
import { getPotenCusById } from '@/api/potenCus/customer/potenCusManage';
import { queryQuestionnaireByType } from '@/api/customerCare/visitRules/questionnaireMake';

export default {
  name: 'DownfeedbackBase',
  mixins: [dictionary],
  props: {
    type: String,
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    return {
      formList: this.createFormList(),
      downFormList: this.createDownFormList(),
      feedbackFormList: this.createFeedbackFormList(),
      columns: this.createCarTableColumns(),
      contactColumns: this.createContactTableColumns(),
      saveData: {},
      cartablelist: [], //调用接口
      contacttablelist: [],
      questionnaire: ''
    };
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  created() {
    this.init();
    this.getAllHeatUp();
  },
  methods: {
    init() {
      getPotenCusById(this.rowData.customerBusinessId,70241002).then(res=>{
        if(res.resultCode == 200){
          this.formList.forEach(x => {
            let value = res.data[x.fieldName];
            if(value && this.isNumber(value)){
              value = parseInt(value);
            }
            x.initialValue = value;
          })
          this.downFormList.forEach(x => {
            let value = this.rowData[x.fieldName];
            if(value&&value!=''){
              if(value && this.isNumber(value)){
                value = parseInt(value);
              }
              x.initialValue = value;
              if(x.fieldName === 'reviewDate'){
                x.initialValue = formatdate(new Date(parseInt(x.initialValue)), 1);
              }
            }
          });

          this.feedbackFormList.forEach(x => {
            let value = this.rowData[x.fieldName];
            if(value&&value!=''){
              if(value && this.isNumber(value)){
                value = parseInt(value);
              }
              x.initialValue = value;
              if(x.fieldName === 'latestVisitDate'){
                x.initialValue = formatdate(new Date(parseInt(x.initialValue)), 1);
              }
              if(x.fieldName === 'visitResult'&&x.initialValue == 15921001){
                x.initialValue = '';
              }
            }
          })

          if(this.type == 'show'){
            this.createdQuestionnaire(this.rowData.questionnaireId,this.rowData.customerVisitTaskId,10421049);
          }

          this.cartablelist = res.data["clueIntentDTOList"];
          this.contacttablelist = res.data["customerContactinfoDTO"];
        }else{
          this.$message.error('获取潜客信息失败!');
        }
      });
      queryQuestionnaireByType({"questionnaireType":15721007}).then(res=>{
        if(res.resultCode == 200){
          this.feedbackFormList.find(item=>item.fieldName=='questionnaireId').itemList = res.data.map(x => ({ value: x.questionnaireId, text: x.questionnaireName }));
        }else{
          this.$message.error('获取问卷失败!');
        }
      });
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          disabled: true,
          label: '客户姓名',
          fieldName: 'customerName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '客户类型',
          fieldName: 'customerType',
          placeholder: '请选择',
          itemList: this.createDictList('1523')
        },
        {
          type: 'INPUT',
          disabled: true,
          label: '联系人姓名',
          fieldName: 'contactName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '性别',
          fieldName: 'gender',
          placeholder: '请选择',
          itemList: this.createDictList('1002')
        },
        {
          type: 'INPUT',
          disabled: true,
          label: '手机号码',
          fieldName: 'mobilePhone',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          disabled: true,
          label: '线索来源',
          fieldName: 'clueSourceName',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          disabled: true,
          label: '来源备注',
          fieldName: 'clueSourceRemark',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '线索热度',
          fieldName: 'temperature',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '意向级别',
          fieldName: 'intentLevel',
          placeholder: '请选择',
          itemList: this.createDictList('1519')
        },
        {
          type: 'DATE',
          disabled: true,
          label: '预购日期',
          fieldName: 'bookingDate',
          placeholder: '请选择'
        },
        {
          type: 'DATE',
          disabled: true,
          label: '期望用车日期',
          fieldName: 'expectedCarDate',
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '潜客类型',
          fieldName: 'clueEnterType',
          placeholder: '请选择',
          itemList: this.createDictList('7019')
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '购买类型',
          fieldName: 'buyType',
          placeholder: '请选择',
          itemList: this.createDictList('1535')
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '业务分类',
          fieldName: 'businessClassify',
          placeholder: '请选择',
          itemList: this.createDictList('7056')
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '付款方式',
          fieldName: 'paymentMethod',
          placeholder: '请选择',
          itemList: this.createDictList('1426')
        },
        {
          type: 'SELECT',
          disabled: true,
          label: '所属顾问',
          fieldName: 'consultantName',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT',
          disabled: true,
          label: '备注',
          fieldName: 'remark',
          placeholder: '请输入...'
        }
      ];
    },
    createCarTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '意向品牌',
          dataIndex: 'intentBrandName',
          sorter: true,
          width: 200,
          filterType: 'input',
        },
        {
          title: '意向车系',
          dataIndex: 'intentSeriesName',
          sorter: true,
          filterType: 'input',
        },
        {
          title: '意向车型',
          dataIndex: 'intentModelName',
          sorter: true,
          width: 100,
          filterType: 'input',
        },
        {
          title: '意向配置',
          dataIndex: 'intentPackageName',
          sorter: true,
          width: 150,
          filterType: 'input',
        },
        {
          title: '意向颜色',
          dataIndex: 'intentColorName',
          sorter: true,
          width: 150,
          filterType: 'input',
        },
        {
          title: '购买备注',
          dataIndex: 'remark',
          sorter: true,
          filterType: 'input',
        }
      ];
    },
    createContactTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '联系人姓名',
          dataIndex: 'contactName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '性别',
          dataIndex: 'gender',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1002'),
          render: props => {
            return <span>{this.createDictText(props.row.gender, '1002')}</span>;
          }
        },
        {
          title: '联系人手机',
          dataIndex: 'contactorPhone',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系人类型',
          dataIndex: 'contactType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('7034'),
          render: props => {
            return <span>{this.createDictText(props.row.contactType, '7034')}</span>;
          }
        },
        {
          title: '关系',
          dataIndex: 'contactRelation',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1534'),
          render: props => {
            return <span>{this.createDictText(props.row.contactRelation, '1534')}</span>;
          }
        },
        {
          title: '备注',
          dataIndex: 'contactRemark',
          sorter: true,
          filter: true,
          filterType: 'input',
        }
      ];
    },
    createDownFormList() {
      return [
        {
          type: 'INPUT',
          label: '战败日期',
          disabled: true,
          fieldName: 'reviewDate'
        },
        {
          type: 'INPUT',
          label: '战败原因',
          disabled: true,
          fieldName: 'resultReason'
        },
        {
          type: 'INPUT',
          label: '战败品牌',
          disabled: true,
          fieldName: 'failBrand'
        },
        {
          type: 'INPUT',
          label: '战败车系',
          disabled: true,
          fieldName: 'failSeries'
        },
        {
          type: 'INPUT',
          label: '经过情形',
          disabled: true,
          fieldName: 'scene'
        }
      ];
    },
    createFeedbackFormList() {
      return [
        {
          type: 'INPUT',
          label: '最晚回访时间',
          fieldName: 'latestVisitDate',
          disabled: true,
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '回访问卷',
          fieldName: 'questionnaireId',
          disabled: true,
          placeholder: '请选择',
          itemList: [],
          change: val=>{
            this.questionnaire = "";
            this.createdQuestionnaire(val,this.rowData.potentialCustomersId,10421049);
          }
        },
        {
          type: 'SELECT',
          label: '回访结果',
          fieldName: 'visitResult',
          placeholder: '请选择',
          itemList: this.filterDict("15921002,15921003,15921004",1592),
          rules: [{ required: true, message: '选择回访结果', trigger: 'change' }],
          change: val=>{
            if(val == 15921004){
              this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').disabled = false;
              this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').rules = [{ required: true, message: '选择关爱失败原因', trigger: 'change' }];
              this.feedbackFormList.find(item=>item.fieldName==='activationStatus').initialValue = 10041002;
              this.feedbackFormList.find(item=>item.fieldName==='activationStatus').disabled = true;
              this.feedbackFormList.find(item=>item.fieldName==='activationStatus').rules = [];
            }else if(val == 15921003){
              this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').initialValue = '';
              this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').disabled = true;
              this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').rules = [];
              this.feedbackFormList.find(item=>item.fieldName==='activationStatus').disabled = false;
              this.feedbackFormList.find(item=>item.fieldName==='activationStatus').rules = [{ required: true, message: '选择是否激活', trigger: 'change' }];
            }else{
              this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').initialValue = '';
              this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').disabled = true;
              this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').rules = [];
              this.feedbackFormList.find(item=>item.fieldName==='activationStatus').initialValue = 10041002;
              this.feedbackFormList.find(item=>item.fieldName==='activationStatus').disabled = true;
              this.feedbackFormList.find(item=>item.fieldName==='activationStatus').rules = [];
            }
            if(val == 15921002||val == 15921001){
              this.feedbackFormList.find(item=>item.fieldName==='questionnaireId').disabled = true;
              this.feedbackFormList.find(item=>item.fieldName==='questionnaireId').initialValue = '';
              this.questionnaire = "";
            }else{
              this.feedbackFormList.find(item=>item.fieldName==='questionnaireId').disabled = false;
            }
            this.feedbackFormList.find(item=>item.fieldName==='visitResult').initialValue = val;
          }
        },
        {
          type: 'SELECT',
          label: '是否激活',
          fieldName: 'activationStatus',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '选择是否激活', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '失败原因',
          fieldName: 'careFailureReason',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('1594')
        },
        {
          type: 'INPUT',
          label: '回访内容',
          fieldName: 'visitContent',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入回访内容', trigger: 'blur' }]
        }
      ];
    },
    isNumber(value) {
      return !isNaN(value);
    },
    //过滤CODE下拉值
    filterDict(codeStr,dict){
      if(codeStr&&codeStr!=""){
        let dictList = this.createDictList(dict);
        let res = [];
        for(let i=0;i<dictList.length;i++){
          if(codeStr.indexOf(dictList[i].value) != -1){
            res.push(dictList[i]);
          }
        }
        return res;
      }
      return "";
    },
    createdQuestionnaire(questionnaireId,billId,billType){
      if(!questionnaireId||questionnaireId==''){
        return;
      }
      let html = "<div id='questionnaire'>";
      let data = {};
      if(this.type == 'show'){
        data = {"questionnaireId":questionnaireId,"billId":billId,"billType":billType};
      }else{
        data = {"questionnaireId":questionnaireId};
      }
      getQuestionnaire(data).then(res=>{
        if(res.resultCode == 200){
          let i=0;
          res.data.forEach(row => {
            html += this.formatQuestionnaire(row,++i);
          })

          html += "</div>";
          this.questionnaire = html;
        }
      })
    },
    formatQuestionnaire(row,i){
      let isMustFilled = row.isMustFilled==10041001?"*":"";
      let html = "<div questionType='"+row.questionType+"' questionName='"+row.questionName+"' questionContent='"+row.questionContent+"' answerQuestionnaireId='"+row.answerQuestionnaireId+"' answerGroupId='"+row.answerGroupId+"' id='"+row.questionId+"' isMustFilled='"+row.isMustFilled+"'>"+i+"."+isMustFilled+"问题："+row.questionName;
      let isDisabeld = this.type == 'show'?"disabled":"";
      if(row.questionType === 15711001||row.questionType === 15711002){
        html += "<div style='margin-left:20px'>";
        row.answerList.forEach(answer=>{
          let isChecked = answer.isChecked==10041001?"checked":"";
          let type = row.questionType == 15711001?"radio":"checkbox";
          html+="<label><input answerUsedId='"+answer.answerUsedId+"' answerSort='"+answer.answerSort+"' answerQuestionnaireId='"+answer.answerQuestionnaireId+"' answerId='"+answer.answerId+"' answer='"+answer.answer+"' id='"+row.questionId+"' "+isDisabeld+" "+isChecked+" name='"+row.questionId+"' type='"+type+"' value='' />"+answer.answer+" </label>";
        })
        html+="</div>";
      }else if(row.questionType === 15711003){
        if(row.value == null){
          row.value = '';
        }
        html+="<div style='margin-left:20px'><textarea "+isDisabeld+" id='"+row.questionId+"' value="+row.value+" rows='2' style='width:500px;'>"+row.value+"</textarea></div>";
      }
      html+="</div>";
      return html;
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async saveDialog() {
      this.$refs.feedbackFormPanel.SUBMIT_FORM();
      this.saveData.questionnaireId = this.feedbackFormList.find(item=>item.fieldName==='questionnaireId').initialValue;
      if(this.saveData.questionnaireId&&this.saveData.questionnaireId!=''){
        this.saveData.billType = 10421049;
      }
      this.saveData.visitResult = this.feedbackFormList.find(item=>item.fieldName==='visitResult').initialValue;
      this.saveData.visitContent = this.feedbackFormList.find(item=>item.fieldName==='visitContent').initialValue;
      this.saveData.activationStatus = this.feedbackFormList.find(item=>item.fieldName==='activationStatus').initialValue;
      this.saveData.careFailureReason = this.feedbackFormList.find(item=>item.fieldName==='careFailureReason').initialValue;
      this.saveData.customerVisitTaskId = this.rowData.customerVisitTaskId;

      var questionnaireDom = document.getElementById("questionnaire");
      if(questionnaireDom){
        let questionnaireList = [];
        let questionnaireChildren = questionnaireDom.children;
        let validate = 0;
        for(let i=0;i<questionnaireChildren.length;i++){
          let dom = questionnaireChildren[i];
          let questionnaire = {};
          questionnaire.questionnaireId = this.feedbackFormList.find(item=>item.fieldName==='questionnaireId').initialValue;
          questionnaire.answerGroupId = dom.getAttribute("answerGroupId");
          questionnaire.answerQuestionnaireId = dom.getAttribute("answerQuestionnaireId");
          questionnaire.isMustFilled = dom.getAttribute("isMustFilled");
          questionnaire.questionContent = dom.getAttribute("questionContent");
          questionnaire.questionId = dom.getAttribute("id");
          questionnaire.questionName = dom.getAttribute("questionName");
          questionnaire.questionType = dom.getAttribute("questionType");
          if(dom.getAttribute("questionType")==15711003){
            let textareaVal = dom.children[0].getElementsByTagName('textarea')[0].value;
            if(dom.getAttribute("isMustFilled")==10041001&&(!textareaVal||textareaVal=="")){
              validate++;
            }
            questionnaire.value = textareaVal;
          }else{
            let answerList = [];
            let answerIds = "";
            let answerChildren = dom.children[0].getElementsByTagName("input");
            for(let i=0;i<answerChildren.length;i++){
              let answer = {};
              let answerDom = answerChildren[i];
              answer.answer = answerDom.getAttribute("answer");
              answer.answerId = answerDom.getAttribute("answerId");
              answer.answerQuestionnaireId = answerDom.getAttribute("answerQuestionnaireId");
              answer.answerSort = answerDom.getAttribute("answerSort");
              answer.answerUsedId = answerDom.getAttribute("answerUsedId");
              if(answerDom.checked){
                answer.isChecked = 10041001;
                answerIds += answerDom.getAttribute("answerId")+",";
              }else{
                answer.isChecked = 10041002;
              }
              answerList.push(answer);
              questionnaire.answerList = answerList;
            }
            if(answerIds!=""){
              questionnaire.value = answerIds.substring(0,answerIds.length-1);
            }else{
              if(dom.getAttribute("isMustFilled")==10041001){
                validate++;
              }
            }
          }
          questionnaireList.push(questionnaire);
        }
        if(validate>0){
          this.$message.error('问卷中有必填项没有填写,无法保存!');
          return;
        }
        this.saveData.questionVisitInfoDTO = questionnaireList;
      }else{
        this.saveData.questionVisitInfoDTO = [];
      }
      saveFeedback(this.saveData).then(res=>{
        if(res.resultCode == 200){
          this.closeDialog('refresh');
        }else{
          this.$message.error('保存失败');
        }
      });
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    }
  }
};
</script>

<style lang="less" scoped>
  .headTitle{
    background: #f2f4f8;
    padding: 10px 0;
    margin-bottom: 10px;
    text-indent: 20px;
  }
</style>
